<template>
	<view>

		<view class="address-container">
			<view class="from">
				<text>{{ from.address }}</text>
			</view>
			<view class="dashed-line"></view>
			<view class="to">
				<text>{{ to.address }}</text>
			</view>
		</view>

		<view v-if="inPorcessOrder != null" class="order-process" @click="toOrder">您有进行中的订单,点击查看</view>

		<map id="map" :longitude="from.longitude" :latitude="from.latitude" :style="contentStyle" scale="14"
			:enable-traffic="false" :show-location="true" class="map" :polyline="polyline" :markers="markers"></map>

		<view class="panel">
			<view class="row">
				<view class="info">
					<view class="label">全程</view>
					<view class="value">
						<text>{{ distance }}</text>
						公里
					</view>
					<view class="label">，预计</view>
					<view class="value">
						<text>{{ duration }}</text>
						分钟
					</view>
				</view>
				<view class="opt" @tap="chooseCarHandle" v-if="!showCar">选择车辆</view>
				<view class="opt" @tap="chooseCarHandle" v-if="showCar">{{ car.carType }}{{ car.carPlate }}</view>
			</view>
			<button class="btn" @tap="createOrderHandle">呼叫代驾</button>
		</view>

		<u-popup v-model="showPopup" mode="center" width="600" height="280" :mask-close-able="false">
			<view class="popup-title">您的订单正在等待司机接单</view>
			<view class="count-down">
				<u-count-down ref="uCountDown" :timestamp="timestamp" :autoplay="false" separator="zh"
					:show-hours="false" :show-border="true" bg-color="#DDF0FF" separator-color="#0083F3"
					border-color="#0D90FF" color="#0D90FF" font-size="32" @end="cancelHandle"
					@change="changeHandle"></u-count-down>

			</view>
			<button class="btn" @tap="cancelHandle">取消订单</button>
		</u-popup>

		<u-top-tips ref="uTips"></u-top-tips>
		<u-modal v-model="uModalShow" show-confirm-button="继续等待" show-cancel-button="确定取消" @confirm="confirm"
			ref="uModal" :async-close="true"></u-modal>

	</view>
</template>

<script>
	let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
	let qqmapsdk;

	export default {
		data() {
			return {
				//窗口样式
				contentStyle: '',
				windowHeight: 0,
				//地图组件
				map: null,
				//订单路线：开始位置和结束位子
				from: {
					address: '',
					longitude: 0,
					latitude: 0
				},
				to: {
					address: '',
					longitude: 0,
					latitude: 0
				},
				//路线规划，路线坐标和图标
				polyline: [],
				markers: [],
				//距离和时长
				distance: 0,
				duration: 0,
				//乘客选择的车辆
				car: {
					carPlate: null,
					carType: null,
				},
				//展示车辆
				showCar: false,
				//倒计时
				showPopup: false,
				timestampStaring: false,
				timestamp: 0,
				//接单的定时任务
				acceptOrderTimer: null,
				uModalShow: false,
				//订单编号
				orderNo: null,
				//是否有进行中的订单
				inPorcessOrder: null
			};
		},
		methods: {
			//初始化窗口样式
			initStyle() {
				const _this = this;
				//处理窗口样式
				const windowHeight = uni.getSystemInfoSync().windowHeight;
				_this.windowHeight = windowHeight;
				_this.contentStyle = `height:${_this.windowHeight}px;`;
			},
			//初始化地图
			initMap() {
				const _this = this;
				//uniapp地图
				_this.map = uni.createMapContext("map", _this);
				//腾讯地图
				qqmapsdk = new QQMapWX({
					key: _this.Constants.QQMAP_KEY
				});
			},
			//初始化位置信息
			initLoaction() {
				const _this = this;
				_this.from = uni.getStorageSync("from");
				_this.to = uni.getStorageSync("to");
			},
			//初始化标记点
			initMarkers() {
				const _this = this;
				_this.markers = [{
					id: 0,
					latitude: _this.from.latitude,
					longitude: _this.from.longitude,
					iconPath: '/static/order/start.png',
					width: 25,
					height: 37
				}, {
					id: 1,
					latitude: _this.to.latitude,
					longitude: _this.to.longitude,
					iconPath: '/static/order/end.png',
					width: 25,
					height: 37
				}]
			},
			//路线规划
			markLine() {
				const _this = this;
				//调用距离计算接口
				qqmapsdk.direction({
					mode: 'driving', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
					//from参数不填默认当前地址
					from: _this.from,
					to: _this.to,
					success: function(res) {
						console.log("---路线规划成功---");
						console.log(res);
						let ret = res;
						let coors = ret.result.routes[0].polyline,
							pl = [];
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						let kr = 1000000;
						for (let i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						};
						//将解压后的坐标放入点串数组pl中
						for (let i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							})
						};
						console.log(pl);
						//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
						_this.polyline = [{
							points: pl,
							color: '#FF0000DD',
							width: 4
						}];
						_this.distance = (res.result.routes[0].distance / 1000).toFixed(2);
						_this.duration = res.result.routes[0].duration;
					},
					fail: function(error) {
						console.error(error);
					}
				});
			},
			//选择车辆
			chooseCarHandle() {
				uni.navigateTo({
					url: "/pages/car_list/car_list"
				})
			},
			//查看选择车辆
			getCar() {
				const _this = this;
				_this.car = uni.getStorageSync("car");
				if (_this.car) {
					_this.showCar = true;
				} else {
					_this.showCar = false;
				}
			},
			//呼叫代驾
			createOrderHandle() {
				const _this = this;
				if (_this.inPorcessOrder == null) {
					const param = {
						"startPlace": _this.from.address,
						"startPlaceLongitude": _this.from.longitude,
						"startPlaceLatitude": _this.from.latitude,
						"endPlace": _this.to.address,
						"endPlaceLongitude": _this.to.longitude,
						"endPlaceLatitude": _this.to.latitude,
						"expectsMileage": _this.distance,
						"expectMinutes": _this.duration,
						"carType": _this.car.carType,
						"carPlate": _this.car.carPlate,
					}
					_this.post("/order/app/order/createOrder", param, (res) => {
						let {
							success,
							message,
							data
						} = res;
						if (success) {
							_this.orderNo = data.orderNo;
							uni.setStorageSync("orderNo",data.orderNo)
							_this.startCountDown(_this.Constants.DefaultCountdown);
						} else {
							uni.showToast({
								title: message,
								icon: "error"
							})
						}
					})
				} else {
					_this.toOrder();
				}
			},
			//执行倒计时
			startCountDown(timestamp) {
				const _this = this;
				//打开弹出
				_this.showPopup = true;
				//设置倒计时时长
				_this.timestamp = timestamp;
			},
			//乘客取消订单,删除redis中的订单
			cancelHandle() {
				const _this = this;
				_this.get("/order/app/order/customer/cancelOrder/" + _this.orderNo, (res) => {
					if (res.success) {
						console.log("---取消订单成功---")
						//关闭弹窗
						_this.showPopup = false;
						//设置倒计时为 0
						_this.timestamp = 0;
					} else {
						uni.showToast({
							title: res.message,
							icon: "error"
						})
					}
				})
			},
			//倒计时查询当前订单
			changeHandle() {
				const _this = this;
				_this.get("/order/app/order/customer/schedule/orderAccept/" + _this.orderNo, (res) => {
					let {
						success,
						message,
						data
					} = res;
					if (success) {
						if(data == true){
							//关闭弹窗
							_this.showPopup = false;
							//设置倒计时为 0
							_this.timestamp = 0;
							uni.navigateTo({
								url: "/pages/move/move?orderNo=" + _this.orderNo
							});
						}
					}else{
						uni.showToast({
							title: message,
							icon: "error"
						})
					}
				})
			},
			//查询最后一次接单状态
			getCustomerOrderStatus(callback) {
				const _this = this;
				_this.get("/order/app/order/customer/lastOrder", (res) => {
					let {
						success,
						message,
						data
					} = res;
					if (success && data) {
						console.log("---获取最近一次订单成功---")
						if (data.status == _this.Constants.OrderStatus.ORDER_STATUS_WAIT ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_ACCEPTED ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_ARRIVE ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_START_DRIVING ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_COMPLETE_DRIVED ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_ENSURE ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_NOT_PAY) {
							_this.inPorcessOrder = data;
						}else{
							_this.inPorcessOrder = null;
						}
					}
					if (typeof callback === 'function') {
						callback(); // 数据更新后执行回调
					}
				});
			},
			//根据订单状态跳转页面
			toOrder() {
				console.log("------------执行toOrder----------------");
				const _this = this;
				_this.getCustomerOrderStatus(function() {
					if (_this.inPorcessOrder) {
						_this.processOrder();
					}
				});
			},
			// 根据订单状态跳转页面--处理逻辑
			processOrder() {
				const _this = this;
				if (_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_WAIT) {
					const date = new Date;
					const countdownTime = ((new Date(_this.inPorcessOrder.createTime).getTime() + 60000) - date
					.getTime()) / 1000;
					if (countdownTime > 0) {
						_this.orderNo = _this.inPorcessOrder.orderNo;
						_this.startCountDown(countdownTime);
					} else {
						_this.inPorcessOrder = null;
						uni.showToast({
							title: "订单已超时",
							icon: "success"
						});
					}
				} else if (_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_ACCEPTED ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_ARRIVE ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_START_DRIVING) {
					uni.navigateTo({
						url: "/pages/move/move?orderNo=" + _this.inPorcessOrder.orderNo
					});
				} else if (_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_COMPLETE_DRIVED ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_ENSURE ||
					_this.inPorcessOrder.status == _this.Constants.OrderStatus.ORDER_STATUS_NOT_PAY) {
					uni.navigateTo({
						url: "/pages/order/order?orderNo=" + _this.inPorcessOrder.orderNo
					});
				}
			}
		},
		onLoad: function(options) {
			const _this = this;
			//初始化窗口样式
			_this.initStyle();
			//初始化地图
			_this.initMap();
			//初始化位置信息
			_this.initLoaction();
			//初始化标记点
			_this.initMarkers();
			//开启计时器
			_this.$refs.uCountDown.start();

			_this.orderNo = options.orderNo;
		},
		onShow() {
			const _this = this;
			//路线规划
			_this.markLine();
			//查看选择车辆
			_this.getCar();
			//根据页面跳转方式执行不同的结果
			if (_this.orderNo) {
				_this.toOrder();
			} else {
				//查询接单状态
				_this.getCustomerOrderStatus();
			}
		}
	};
</script>

<style lang="less">
	@import url('create_order.less');
</style>